%Beta Bayes estimation
function [betabayes]  = BetaBayes(rStock,rIndex,market,index)
    rolling = 260;
    n = length(rStock);
    k = n-rolling;
    
%     query = strcat('select m.ID from market m where m.name=', '''', market, ''';');
%     marketID = selectData(query);
%     marketID = marketID{1}
%     
%     query = strcat('select s.Name from security s where s.ID_Market =',  int2str(marketID), ';');
%     stocklist = selectData(query);
%     
%     %Initial Parameter
%     n = length(stocklist);
%     for i=1:n
%       if (strcmp(stocklist{i},'CTT') == 0)
%       stocklist{i}
%       [a b c pStocktemp pIndextemp] = getStock_Index(stocklist{i},index);
%       rStocktemp = getReturn(pStocktemp);
%       rIndextemp = getReturn(pIndextemp);
%       bo(i) = regress(rStocktemp,rIndextemp);
%       end
%     end 
    if (strcmp(market,'HOSE'))
        betapr = 0.8287;%mean(bo)
        varbetpr = 0.3;%std(bo)
    else if (strcmp(market,'HNX'))
        betapr = 0.7733;%mean(bo)
        varbetpr = 0.3945;%std(bo)
        end
    end
    
    [n,m]=size(rStock);
    X= [ones(n,1),rIndex];
    y=rStock;
    %QR Decomposition X
    [Q,R]=qr(X,0);
    
    %Regression Coefficients 
    beta = R\(Q'*y);
    
    %Fitted Values of the Response 
    yhat = X*beta;
    
    %Residuals
    residuals = y - yhat;
    
    %Mean Squared Error 
    nobs = length(y);
    p = min(size(R));
    dfe = nobs-p;
    mse = sum(residuals.*residuals)./dfe;
    sse=sum(residuals.*residuals);
    
    %Hat (Projection) Matrix 
    hatmat = Q*Q';
    yhat = hatmat*y;
    
    %Covariance Matrix of Estimated Coefficients 
    ri = R\eye(p); % inverse of R
    xtxi = ri*ri'; % equivalent to inv(X'*X)
    covb = xtxi*mse;
    
    coeff = (R\(Q'*y))';
    
    %Stima Bayes
    meanind=mean(rIndex);
    varres=var(residuals);
    v=sum((rIndex(:,1)-meanind).^2);
    varols=varres/v;
    varbayes=1/(1/varols+1/varbetpr);
    w=varbayes/varbetpr;
    beta=w*betapr+(1-w)*coeff;
    betabayes=beta(2);
end
